package com.cuotibao.zhuoxiao.basics;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;

/**
 * @author hdx on 2019/5/6.
 */
public abstract class BaseFragment extends Fragment {

    protected Context mContext;
    private ProgressDialog mProgressDlg;

    protected boolean isFirstDownLoad = true;
    protected View rootView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rootView = view;
    }

    @SuppressLint("NewApi")
    public void showProgressDialog(String message) {
        if (mProgressDlg == null && mContext != null && !((Activity) mContext).isFinishing() && !((Activity) mContext).isDestroyed()) {
            mProgressDlg = new ProgressDialog(mContext);
            mProgressDlg.setMessage(message);
            mProgressDlg.setCanceledOnTouchOutside(false);
            // mProgressDlg.setCanceledOnTouchOutside(false);
            // mProgressDlg.setCancelable(false);
            mProgressDlg.show();
        }
    }

    @SuppressLint("NewApi")
    public void setProgressDialogMessage(String message) {
        if (mProgressDlg != null && mProgressDlg.isShowing()) {
            Context context = ((ContextWrapper) mProgressDlg.getContext()).getBaseContext();
            if (context instanceof Activity) {
                if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed())
                    mProgressDlg.setMessage(message);
            } else {
                mProgressDlg.setMessage(message);
            }
        }
    }

    @SuppressLint("NewApi")
    public void dismissProgressDialog() {
        if (mProgressDlg != null && mProgressDlg.isShowing()) {
            Context context = ((ContextWrapper) mProgressDlg.getContext()).getBaseContext();
            if (context instanceof Activity) {
                if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed())
                    mProgressDlg.dismiss();
            } else {
                mProgressDlg.dismiss();
            }
        }
        mProgressDlg = null;
    }
}
